package tests;

import common.Utils;
import constant.Constants;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;

public class LoginPage extends Utils {

    public LoginPage() {
        driver.get(Constants.LOGIN_DEFAULT_PATH);
    }

    /**
     * 检查页面是否成功加载
     */
    public void loginPageRight() {
        // 检查页面元素 -> 页面是否加载成功
        // 登录标题
        String title = driver.findElement(By.cssSelector("body > div.container-login > div.login-dialog > h3")).getText();
        assert title.equals("登录");
        // 用户名
        String userName = driver.findElement(By.cssSelector("body > div.container-login > div.login-dialog > div:nth-child(2) > span")).getText();
        assert userName.equals("用户名");
        // 密码
        String password = driver.findElement(By.cssSelector("body > div.container-login > div.login-dialog > div:nth-child(3) > span")).getText();
        assert password.equals("密码");
        // 输入框是否存在
        driver.findElement(By.cssSelector("#userName"));
        driver.findElement(By.cssSelector("#password"));
    }

    /**
     * 登录成功
     */
    public void loginSuccess() {
        driver.findElement(By.cssSelector("#userName")).clear();
        driver.findElement(By.cssSelector("#password")).clear();
        // 输入账号 密码
        driver.findElement(By.cssSelector("#userName")).sendKeys("ppp");
        driver.findElement(By.cssSelector("#password")).sendKeys("ppp");
        // 点击登录
        driver.findElement(By.cssSelector("body > div.container-login > div.login-dialog > div:nth-child(5) > button")).click();
        // 检查是否登录成
        String title = driver.findElement(By.cssSelector("body > div.bookContainer > h2")).getText();
        assert title.equals("图书列表");
        // 截图
        getScreenShot(getClass().getName());
        // 退回登录页面
        driver.navigate().back();
    }

    public void loginFail() {
        driver.findElement(By.cssSelector("#userName")).clear();
        driver.findElement(By.cssSelector("#password")).clear();
        // 输入账号 密码
        driver.findElement(By.cssSelector("#userName")).sendKeys("");
        driver.findElement(By.cssSelector("#password")).sendKeys("");
        // 点击登录
        driver.findElement(By.cssSelector("body > div.container-login > div.login-dialog > div:nth-child(5) > button")).click();
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        // 处理弹窗
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Alert alert = driver.switchTo().alert();
        alert.accept();
        // 获取元素
        String title = driver.findElement(By.cssSelector("body > div.container-login > div.login-dialog > h3")).getText();
        assert title.equals("登录");
    }
}
